package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.aliyuncs.exceptions.ClientException;
import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Action(value="customer_sendSms",results={})
	public String sendSms() throws Exception{
		System.out.println(model.getTelephone());
		//随机生成5位数字
		String code = RandomStringUtils.randomNumeric(5);
		//将生成的数字存入session中
		System.out.println("验证码："+code);
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), code);
		
			//SmsUtils.sendCode(model.getTelephone(), code);
		
		//调用mq发送消息
		jmsTemplate.send("bos_sms",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				// TODO Auto-generated method stub
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone",model.getTelephone());
				mapMessage.setString("code",code);
				return mapMessage;
			}
		});
		
		return NONE;
	}
	private String checkCode;
	
	
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}
	@Autowired
	private RedisTemplate< String, String> redisTemplate;


	@Action(value="customer_regist",results={@Result(name="success",type="redirect",location="signup-success.html")
	,@Result(name="input",type="redirect",location="signup.html")})
	public String regist(){
		System.out.println("手--验证码"+checkCode);
		String tCode =(String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		System.out.println("session--验证码"+tCode);
		if(tCode==null||!tCode.equals(checkCode)){
			System.out.println("验证码错误");
			return "input";
		}
		//调用webservice，连接crm，保存客户
		WebClient.create("http://localhost:9002/crm_management/services/customerService/customer")
		.type(MediaType.APPLICATION_JSON).post(model);
		//发送邮件
		// 发送一封激活邮件
		// 生成激活码
		String activecode = RandomStringUtils.randomNumeric(32);

		// 将激活码保存到redis，设置24小时失效
		System.out.println(model.getTelephone());
		System.out.println(activecode);
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24,
				TimeUnit.SECONDS);

		// 调用MailUtils发送激活邮件
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		//ActionContext.getContext().getValueStack().set("mail",  model.getEmail());
		System.out.println("注册成功");
		return SUCCESS;
	}
	@Action(value="customer_mailAction")
	public String activeMail() throws IOException  {
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		// 判断激活码是否有效
		String activecodeRedis = redisTemplate.opsForValue().get(
				model.getTelephone());
		if (activecodeRedis == null || !activecodeRedis.equals(activecodeRedis)) {
			// 激活码无效
			ServletActionContext.getResponse().getWriter()
					.println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			// 激活码有效
			// 防止重复绑定
			// 调用CRM webService 查询客户信息，判断是否已经绑定
			Customer customer = WebClient
					.create("http://localhost:9002/crm_management/services"
							+ "/customerService/customer/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() == null || customer.getType() != 1) {
				// 没有绑定,进行绑定
				WebClient.create(
						"http://localhost:9002/crm_management/services"
								+ "/customerService/customer/updatetype/"
								+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter()
						.println("邮箱绑定成功！");
			} else {
				// 已经绑定过
				ServletActionContext.getResponse().getWriter()
						.println("邮箱已经绑定过，无需重复绑定！");
			}

			// 删除redis的激活码
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}

}
